package org.vic.strategy.demo03.improve.extended;

import org.vic.strategy.demo03.CalPrice;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.SortedMap;

/**
 * 代理类，处理多重策略计算价格
 * Created by VIC.Huang on 2016/8/24.
 */
public class CalPriceProxy implements InvocationHandler {
    private SortedMap<Integer, Class<? extends CalPrice>> clazzMap;

    public CalPriceProxy(SortedMap<Integer, Class<? extends CalPrice>> clazzMap) {
        this.clazzMap = clazzMap;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Double result = 0D;
        if("calPrice".equals(method.getName())) {
            for(Class<? extends CalPrice> clazz : clazzMap.values()) {   // 有序循环多个策略，对价格进行计算
                Object clazzInstance = clazz.getDeclaredConstructor(DiffType4CalPrice.class).newInstance(DiffType4CalPrice.class.newInstance());
                if(result == 0) {
                    result = (Double)method.invoke(clazzInstance, args);
                }else {
                    result = (Double)method.invoke(clazzInstance, result);
                }
            }
            return result;
        }
        return null;
    }

    public static CalPrice getProxy(SortedMap<Integer, Class<? extends CalPrice>> clazzMap) {
        return (CalPrice)Proxy.newProxyInstance(CalPriceProxy.class.getClassLoader(), new Class<?>[]{CalPrice.class}, new CalPriceProxy(clazzMap));
    }
}
